# -*- coding: utf-8 -*-
import asyncio
import websockets
import json
import mysql.connector
from datetime import datetime

# 创建与数据库的连接
db_connection = mysql.connector.connect(
    host='localhost',
    port=3306,
    user='root',
    password='Cjb77xxh!',
    database='chat29'
)

# 获取数据库游标
db_cursor = db_connection.cursor()

# 用于存储连接的客户端
connected_clients = set()

async def chat_server(websocket, path=None):  # 修改：path 设为可选参数
    # 接收用户发送的昵称
    print(f'Client {websocket.remote_address} connected')
    nickname_message = await websocket.recv()
    nickname_data = json.loads(nickname_message)
    nickname = nickname_data['nickname']

    # 将新连接的客户端加入到已连接的客户端集合中
    connected_clients.add(websocket)

    try:
        # 查询历史消息并发送给新连接的客户端
        db_cursor.execute("SELECT username, content, created_time FROM chat_list ORDER BY created_time DESC LIMIT 10")
        history_messages = db_cursor.fetchall()
        for message in history_messages[::-1]:
            chat_message = {
                'content': message[1],
                'nickname': message[0],
                'timestamp': message[2].strftime('%Y-%m-%d %H:%M:%S'),
                'isSent': False
            }
            await websocket.send(json.dumps(chat_message))

        # 监听客户端发送的消息
        async for message in websocket:
            # 解析消息并获取内容
            message_data = json.loads(message)
            content = message_data['content']

            if content == '/delete':
                # 删除数据库chat_list的所有内容
                db_cursor.execute("DELETE FROM chat_list")
                db_connection.commit()

                # 向所有连接的客户端发送删除消息
                delete_message = {
                    'content': '所有内容已删除',
                    'nickname': '系统消息',
                    'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    'isSent': False
                }

                await asyncio.gather(
                    *[client.send(json.dumps(delete_message)) for client in connected_clients]
                )
            else:
                # 保存消息到数据库
                current_time = datetime.now()
                db_cursor.execute("INSERT INTO chat_list (username, content, created_time) VALUES (%s, %s, %s)",
                                  (nickname, content, current_time))
                db_connection.commit()

                # 构造消息对象，包含内容、昵称和时间戳信息
                chat_message = {
                    'content': content,
                    'nickname': nickname,
                    'timestamp': current_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'isSent': False
                }

                # 将消息发送给除发送者外的所有已连接客户端
                await asyncio.gather(
                    *[client.send(json.dumps(chat_message)) for client in connected_clients if client != websocket]
                )

                # 将消息发送给发送者自身
                chat_message['isSent'] = True
                await websocket.send(json.dumps(chat_message))
    finally:
        # 客户端断开连接后，从已连接的客户端集合中移除
        connected_clients.remove(websocket)

async def main():
    # 启动WebSocket服务器
    async with websockets.serve(chat_server, '127.0.0.1', 8765):
        print("Server is running on '127.0.0.1:8765'")
        await asyncio.Future()  # 永远运行

# 运行主函数
if __name__ == "__main__":
    asyncio.run(main())